set nonumber
set linebreak

function! FindDeadRedirects() abort
  let lines = getline(1, '$')
  for ln in lines
    if ln =~# ' > '
      let label = split(ln, ' > ')[1]
      while label[0] ==# '+' || label[0] ==# '-'
        while label[0] !=# ' '
          let label = label[1:]
        endwhile
        let label = label[1:]
      endwhile
      if index(lines, label) == -1
        echomsg label
      endif
    endif
  endfor
endfunction

function! AutoGrammar(word) abort
  if a:word ==? 'jsi'
    return "\<bs>[i|te]"
  elseif a:word ==# 'ses'
    return "\<c-w>[ses|jste se]"
  elseif a:word ==# 'tě'
    return "\<c-w>[tě|vás]"
  elseif a:word ==# 'tebe'
    return "\<c-w>[tebe|vás]"
  elseif a:word ==# 'ti'
    return "\<c-w>[ti|vám]"
  elseif a:word ==# 'tobě'
    return "\<c-w>[tobě|vá]\<left>"
  elseif a:word ==# 'tebou'
    return "\<c-w>[tebou|vámi]"
  elseif a:word =~# 'te$'
    return "\<bs>\<bs>[|te]"
  elseif a:word =~# 'š$'
    return "\<bs>[š|te]"
  elseif a:word =~# 'el$'
    return "\<bs>\<bs>[el/la]"
  elseif a:word =~# 'l$'
    return "[/a]"
  elseif a:word =~# 'ý$'
    return "\<bs>[ý/á]"
  endif
  return ''
endfunction

function! AutoExpand() abort
  if getline('.') =~# ';$'
    let prevline = matchlist(getline(line('.') - 1), ' > \(.*\)')
    if !empty(prevline)
      return "\<bs> > " .. prevline[1] .. "\<cr>"
    endif
  endif
  return "\<cr>"
endfunction

command FindDeadRedirects call FindDeadRedirects()
inoremap <buffer> <silent> <expr> <plug>(AutoGrammar) "\<right>" .. AutoGrammar(expand('<cword>'))
imap <buffer> <silent> <tab> <left><plug>(AutoGrammar)
inoremap <buffer> <silent> <expr> <cr> AutoExpand()
inoremap <buffer> <silent> <expr> > getline('.') =~# ' $' ? '>' : ' > '
